/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * dlgElejirRack.java
 *
 * Created on Oct 31, 2011, 3:21:07 PM
 */

package visual.Almacenamiento;

import bentity.beRack;
import blogic.blRack;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import visual.Seguridad.visualHelper;

/**
 *
 * @author cesar
 */
public class dlgElejirRack extends javax.swing.JDialog {
     private beRack rackElegido = null;
     public String estado;
     public int idRack = -1;
     public int arreglado = 0;

    /** Creates new form dlgElejirRack */
    public dlgElejirRack(java.awt.Frame parent, boolean modal,int indicador) {
        super(parent, modal);
        initComponents();
        this.consultarRacksPorFiltros(indicador);
        this.setBounds(0, 0, 900, 500);
        tblRacks.setDefaultRenderer(Object.class, new Render());
        this.setResizable(false);
        visualHelper.centrarDialogoEnPantalla(this);

    }

     private void consultarRacksPorFiltros(int indicador){
        try{
            blRack br = new blRack();
            ArrayList<Integer> estados =new ArrayList<Integer>();
            ArrayList<beRack> racks = new ArrayList<beRack>();
            estados = br.getEstados();
            if (indicador == 1) {
                racks = br.obtenerRacks(estados.get(0));

            DefaultTableModel dtm = (DefaultTableModel)this.tblRacks.getModel();
            this.limpiarTabla(dtm);
                if (racks.size() == 0)
                    visualHelper.mostrarMensajeAdvertencia("La búsqueda no arrojó resultados.");
                else
                    this.llenarTabla(racks,indicador);
    //                if (indicador == 2){
    //                    racks =br.obtenerRacks(estados.get(2));
    //                    if(racks.size()!=0)
    //                       this.llenarTabla(racks);
    //                }
            }
            else {
                racks = br.obtenerRaksXIncidentes();
                DefaultTableModel dtm = (DefaultTableModel)this.tblRacks.getModel();
                this.limpiarTabla(dtm);
                if(racks.size()== 0){
                    visualHelper.mostrarMensajeAdvertencia("No hay racks asociados a un incidente");
                }
                else
                    this.llenarTabla(racks,indicador);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            visualHelper.mostrarMensajeError("Ocurrió un error en la búsqueda");
        }
    }
      private void llenarTabla(ArrayList<beRack> racks,int indicador) throws SQLException {
        DefaultTableModel dtm = (DefaultTableModel)this.tblRacks.getModel();
        Object [] datos = new Object [7];
        blRack r = new blRack();
        for(int i=0;i<racks.size();i++){
            datos[0] = racks.get(i).getId_rack();
            String cad = "B"+String.valueOf(racks.get(i).getNumRack())+"-F"+String.valueOf(racks.get(i).getNumFila())+"";
            datos[1] = cad;
            datos[2] = racks.get(i).getCantPiso();
            datos[3] = racks.get(i).getCantUbicaciones();
            
                       
            ArrayList<String> estados = r.obtenerEstados();

            if (racks.get(i).getEstado()== 18 && indicador == 1)
               datos[4] = estados.get(0);
            else {
                 if (racks.get(i).getEstado()== 17)
                    datos[4] = estados.get(2);
                 else
                     if (indicador == 2)
                         datos[4] = "Con Incidente";
            }
            if(indicador == 1)
                datos[5]="----";
            else
                datos[5]= racks.get(i).getDescripcion();
            dtm.addRow(datos);
        }
        this.tblRacks.setRowSelectionAllowed(true);
        this.tblRacks.setColumnSelectionAllowed(false);
    }

    private void limpiarTabla(DefaultTableModel dtm) {
        int numFilas = dtm.getRowCount();
        for(int i=(numFilas-1);i>=0;i--)
            dtm.removeRow(i);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitulo = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblRacks = new javax.swing.JTable();
        lblRacks = new javax.swing.JLabel();
        btnSeleccionar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);
        setModal(true);
        getContentPane().setLayout(null);

        lblTitulo.setFont(new java.awt.Font("DejaVu Sans", 0, 36));
        lblTitulo.setForeground(new java.awt.Color(0, 0, 0));
        lblTitulo.setText("Buscar rack");
        getContentPane().add(lblTitulo);
        lblTitulo.setBounds(310, 30, 240, 43);

        tblRacks.setAutoCreateRowSorter(true);
        tblRacks.setForeground(new java.awt.Color(0, 0, 0));
        tblRacks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CodRack", "Identificador", "CantPisos", "CantUbicaciones", "Estado", "Descripcion"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblRacks.setColumnSelectionAllowed(true);
        tblRacks.setGridColor(javax.swing.UIManager.getDefaults().getColor("TableHeader.background"));
        tblRacks.setMaximumSize(new java.awt.Dimension(800, 72));
        tblRacks.setMinimumSize(new java.awt.Dimension(200, 72));
        tblRacks.setSelectionForeground(new java.awt.Color(0, 0, 0));
        tblRacks.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblRacks.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tblRacks);
        tblRacks.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(30, 110, 800, 230);

        lblRacks.setFont(new java.awt.Font("Dialog", 0, 14));
        lblRacks.setForeground(new java.awt.Color(0, 0, 0));
        lblRacks.setText("Racks");
        getContentPane().add(lblRacks);
        lblRacks.setBounds(30, 90, 80, 17);

        btnSeleccionar.setBackground(new java.awt.Color(240, 235, 226));
        btnSeleccionar.setFont(new java.awt.Font("Dialog", 0, 12));
        btnSeleccionar.setForeground(new java.awt.Color(0, 0, 0));
        btnSeleccionar.setText("Elegir");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });
        getContentPane().add(btnSeleccionar);
        btnSeleccionar.setBounds(230, 400, 120, 27);

        btnCancelar.setBackground(new java.awt.Color(240, 235, 226));
        btnCancelar.setFont(new java.awt.Font("Dialog", 0, 12));
        btnCancelar.setForeground(new java.awt.Color(0, 0, 0));
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar);
        btnCancelar.setBounds(530, 400, 120, 27);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        // TODO add your handling code here:
        int fila = this.tblRacks.getSelectedRow();
        if (fila == -1)
            visualHelper.mostrarMensajeAdvertencia("Debe seleccionar un rack.");
        else{
            if(this.tblRacks.getSelectedRowCount() > 1){
                visualHelper.mostrarMensajeAdvertencia("Debe seleccionar un solo rack");
            }
            else{
                String cad = this.tblRacks.getValueAt(fila,1).toString();
                int inicio = cad.indexOf("F");
                //int fin = cad.indexOf(inicio, cad.length());
                String numRack = cad.substring(1, inicio-1);
                String numFila = cad.substring(inicio+1,cad.length());
                this.rackElegido = new beRack(Integer.parseInt(this.tblRacks.getValueAt(fila, 0).toString()), Integer.parseInt(this.tblRacks.getValueAt(fila, 2).toString()),Integer.parseInt(this.tblRacks.getValueAt(fila, 3).toString()),Integer.parseInt(numRack),Integer.parseInt(numFila),1);
                estado = this.tblRacks.getValueAt(fila,4).toString();
                idRack = Integer.parseInt(this.tblRacks.getValueAt(fila, 0).toString());
                this.setVisible(false);
            }
        }
}//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        int rslt = JOptionPane.showConfirmDialog(this, "¿Está seguro que desea cancelar la busqueda del rack sin cargar los datos?", "Confirmación", JOptionPane.YES_NO_OPTION);
        if (rslt == JOptionPane.YES_OPTION){
            this.setVisible(false);
            this.dispose();
        }

}//GEN-LAST:event_btnCancelarActionPerformed

    public javax.swing.JTable getTblRacks() {
        return tblRacks;
    }

    /**
     * @param tblClientes the tblClientes to set
     */
    public void setTblClientes(javax.swing.JTable tblRacks) {
        this.tblRacks = tblRacks;
    }
    /**
    * @param args the command line arguments
    */
  
    public beRack getRackElegido() {
        return rackElegido;
    }

    /**
     * @param clienteElegido the clienteElegido to set
     */
    public void setRackElegido(beRack rackElegido) {
        this.rackElegido = rackElegido;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblRacks;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTable tblRacks;
    // End of variables declaration//GEN-END:variables

}
